let socket = null;
let gameId = null;
let username = null;
let myColor = null;
const canvas = document.getElementById('gomokuBoard');
const context = canvas.getContext('2d');
const boardSize = 15;
const cellSize = 40;
let board = Array.from({ length: boardSize }, () => Array(boardSize).fill(null));
let currentPlayer = 'black'; // 当前玩家（黑棋或白棋）
const statusDiv = document.getElementById('status');

// 重新开始按钮
const resetButton = document.getElementById('resetButton'); 
// 退出房间按钮
const leaveRoomButton = document.getElementById('leaveRoomButton'); 
const userInputContainer = document.getElementById('userInputContainer');
const gameContainer = document.getElementById('gameContainer');
const colorChoiceContainer = document.getElementById('colorChoiceContainer');

// 处理连接按钮点击事件
document.getElementById('connectButton').addEventListener('click', () => {
    username = document.getElementById('username').value.trim();
    gameId = document.getElementById('gameId').value.trim();
    
    if (username === "" || gameId === "") {
        alert("请输入有效的昵称和房间号");
        return;
    }

    connectToGame(gameId, username);
});

// 连接 WebSocket
function connectToGame(gameId, username) {
    socket = new WebSocket(`ws://localhost:8080/game?gameId=${gameId}&username=${username}`);

    socket.onopen = () => {
        console.log('WebSocket 连接已建立');
        statusDiv.textContent = '连接成功，请选择棋色';
        userInputContainer.style.display = 'none';  // 隐藏输入框
        gameContainer.style.display = 'block';      // 显示棋盘

        // 显示房间号和昵称
        document.getElementById('displayGameId').textContent = gameId;
        document.getElementById('displayUsername').textContent = username;

        
    };

    socket.onmessage = (event) => {
        username = document.getElementById('username').value.trim();
        const message = event.data;
        console.log(message);
        const jsonObject = JSON.parse(message);
         // 将对象转换为 Map
        const messageMap = new Map(Object.entries(jsonObject));
        const type = messageMap.get('type');
        if (type === "startSelectColor") {
            console.log(type);
            // 显示棋色选择
            colorChoiceContainer.style.display = 'block'; // 显示棋色选择器
        }else if(type === "leaveRoom"){
            console.log(type);
            // 断开当前连接
            socket.close();
            document.getElementById('colorChoiceContainer').style.display = 'none';
        }else if(type === "colorSelected"){
            if(username == messageMap.get('userId')){
                if(messageMap.get('successes') == true){
                    if(messageMap.get('blackChecked' && messageMap.get('blackUser') == username)){
                        blackColorButton.style.backgroundColor = 'gray';  // 选中后变成灰色
                        blackColorButton.style.color = 'white';
                        blackColorButton.innerText = '已选择';
                    }else if(messageMap.get('WhiteChecked'&& messageMap.get('whiteUser') == username)){
                        whiteColorButton.style.color = 'black';
                        whiteColorButton.innerText = '已选择';
                        whiteColorButton.style.backgroundColor = 'gray';  // 选中后变成灰色
                    }
                    blackColorButton.disabled = true;
                    whiteColorButton.disabled = true;
                }else if(messageMap.get('successes') == false){
                    alert("棋色已被其他用户选择");
                }
            }else if(username != messageMap.get('userId')){
                if(messageMap.get('successes') == true){
                    if(messageMap.get('blackChecked') && messageMap.get('blackUser') != username){
                        blackColorButton.style.backgroundColor = 'gray';  // 选中后变成灰色
                        blackColorButton.style.color = 'white';
                        blackColorButton.innerText = '对方';
                        blackColorButton.disabled = true;
                    }else if(messageMap.get('WhiteChecked') && messageMap.get('whiteUser') != username){
                        whiteColorButton.style.color = 'black';
                        whiteColorButton.innerText = '对方';
                        whiteColorButton.style.backgroundColor = 'gray';  // 选中后变成灰色
                        whiteColorButton.disabled = true;
                    }
                }
            }
            console.log(type);
        }else if(type === "gameStart"){
             // 隐藏棋色选择容器
            document.getElementById('colorChoiceContainer').style.display = 'none';

            // 显示棋盘
            canvas.style.display = 'block';

            // 清空棋盘
            resetBoard();
    
            // 更新状态提示，显示当前玩家
            statusDiv.textContent = `游戏开始，${myColor === 'black' ? '你是黑棋，先手' : '你是白棋，等待对手下棋'}`;
        }
    };

    socket.onclose = () => {
        console.log('WebSocket 连接已关闭');
        resetInputs();
        userInputContainer.style.display = 'block';  // 重新显示输入框
        gameContainer.style.display = 'none';        // 隐藏棋盘
    };

    socket.onerror = (error) => {
        console.error('WebSocket 错误:', error);
        alert('WebSocket 连接失败，请重试');
        resetInputs();
        userInputContainer.style.display = 'block';  // 重新显示输入框
        gameContainer.style.display = 'none';        // 隐藏棋盘
    };
}

blackColorButton.addEventListener('click', () => {
    // 改变黑色按钮的样式，表示已选中
    blackColorButton.style.backgroundColor = 'gray';  // 选中后变成灰色
    blackColorButton.style.color = 'white';
    blackColorButton.innerText = '已选择黑色';


    // 向服务器发送黑色棋子选择
    const message = {
        type: 'colorSelected',
        color: 'black'
    };
    socket.send(JSON.stringify(message));

    console.log('已选择黑色');
});

// 当点击白色按钮时
whiteColorButton.addEventListener('click', () => {
    // 改变白色按钮的样式，表示已选中
    whiteColorButton.style.backgroundColor = 'gray';  // 选中后变成灰色
    whiteColorButton.style.color = 'black';
    whiteColorButton.innerText = '已选择白色';


    // 向服务器发送白色棋子选择
    const message = {
        type: 'colorSelected',
        color: 'white'
    };
    socket.send(JSON.stringify(message));
    console.log('已选择白色');
});

// 退出房间按钮点击事件
leaveRoomButton.addEventListener('click', () => {
    // 发送退出房间的消息给服务器
    const message = {
        type: 'leaveRoom'
    };
    socket.send(JSON.stringify(message));

    // 断开 WebSocket 连接
    socket.close();
    
    console.log('已退出房间');
    
    // 这里可以添加清理游戏状态的代码，比如重置 UI 等
});

// 监听页面关闭或刷新事件，关闭 WebSocket 连接
window.onbeforeunload = () => {
    if (socket.readyState === WebSocket.OPEN) {
        // 发送离开消息给服务器，告知用户离开
        socket.send(JSON.stringify({ type: 'leaveRoom' }));
        // 关闭 WebSocket 连接
        socket.close();
        console.log('连接关闭，页面已刷新或关闭');
    }
};

// 当页面加载时，恢复选项到默认状态
window.onload = () => {
    // 重置用户名
    resetInputs();
    console.log('页面已刷新，选项恢复到默认设置');
};

function resetInputs() {
    blackColorButton.style.backgroundColor = 'black';
    blackColorButton.style.color = 'white';
    blackColorButton.innerText = '黑色';
    whiteColorButton.style.backgroundColor = 'white';
    whiteColorButton.style.color = 'black';
    whiteColorButton.innerText = '白色';
    whiteColorButton.disabled = false;
    blackColorButton.disabled = false;
    document.getElementById('username').value = ''; // 将昵称输入框置为空
    document.getElementById('gameId').value = '';   // 将房间号输入框置为空
    console.log('用户输入已置空');
}

function resetBoard() {
    // 清空棋盘数据
    board = Array.from({ length: boardSize }, () => Array(boardSize).fill(null));

    // 清空画布
    context.clearRect(0, 0, canvas.width, canvas.height);

    // 绘制棋盘
    drawBoard();
}

function drawBoard() {
    context.strokeStyle = "#000";  // 设置棋盘线条颜色
    for (let i = 0; i < boardSize; i++) {
        for (let j = 0; j < boardSize; j++) {
            // 绘制每个单元格
            context.strokeRect(i * cellSize, j * cellSize, cellSize, cellSize);
        }
    }
}